<template>
  <div class="icon-form">
    <el-form :model="formData" label-width="80px" :rules="rules" ref="formRef">
      <el-form-item label="图标名称" prop="filename">
        <el-input v-model="formData.filename" placeholder="请输入图标名称" clearable />
      </el-form-item>

      <el-form-item label="图标文件" prop="file">
        <div class="upload-preview-container">
          <!-- 上传组件 - 仅当没有预览时显示 -->
          <div v-if="!previewUrl" class="upload-section">
            <el-upload ref="uploadRef" class="icon-upload" action="#" :auto-upload="false" :show-file-list="false"
              :limit="1" :on-change="handleFileChange" :on-remove="handleFileRemove" :on-exceed="handleExceed"
              :before-upload="beforeUpload" accept=".png,.jpg,.jpeg,.svg,.gif" drag>
              <el-icon class="el-icon--upload">
                <upload-filled />
              </el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 PNG、JPG、SVG、GIF 格式，建议尺寸 200x200 以上
                </div>
              </template>
            </el-upload>
          </div>

          <!-- 预览区域 - 仅当有预览时显示 -->
          <div v-if="previewUrl" class="preview-section full-width">
            <div class="preview-header">
              <h4>预览效果</h4>
              <el-button type="danger" circle size="small" @click="handleFileRemove" :icon="Delete" />
            </div>
            <div class="preview-container">
              <img :src="previewUrl" alt="预览" class="preview-image" />
            </div>
            <div class="preview-info">
              <span>{{ formData.file?.name || '未命名文件' }}</span>
              <span>{{ formatFileSize(formData.file?.size) }}</span>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item class="form-actions">
        <el-button type="primary" @click="submitUpload" :loading="uploading" :disabled="!canSubmit || uploading">
          上传图标
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { UploadFilled, Delete } from '@element-plus/icons-vue';
import footballService from '../services/footballService';
const props = defineProps({
  iconType: {
    type: String,
    required: true,
    validator: value => ['team', 'match'].includes(value)
  }
});

const emit = defineEmits(['upload-success']);

const formRef = ref(null);
const uploadRef = ref(null); // 添加上传组件的引用
const fileList = ref([]);
const uploading = ref(false);
const previewUrl = ref('');

// 表单数据
const formData = reactive({
  filename: '',
  file: null
});

// 表单验证规则
const rules = {
  filename: [
    { required: true, message: '请输入图标名称', trigger: 'blur' },
    { min: 2, max: 50, message: '图标名称长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请上传图标文件', trigger: 'change' }
  ]
};

// 图标类型文本
const iconTypeText = computed(() => {
  return props.iconType === 'team' ? '球队' : '比赛';
});

// 是否可以提交
const canSubmit = computed(() => {
  return formData.filename.trim() && formData.file;
});

// 格式化文件大小
function formatFileSize(size) {
  if (!size) return '未知大小';

  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else {
    return (size / 1024 / 1024).toFixed(2) + ' MB';
  }
}

// 监听文件列表变化，更新预览
watch(() => fileList.value, (newFiles) => {
  if (newFiles.length > 0 && newFiles[0].raw) {
    createPreviewUrl(newFiles[0].raw);
  } else {
    clearPreviewUrl();
  }
});

// 创建预览URL
function createPreviewUrl(file) {
  clearPreviewUrl();
  previewUrl.value = URL.createObjectURL(file);
}

// 清理预览URL
function clearPreviewUrl() {
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value);
    previewUrl.value = '';
  }
}

// 文件上传前的验证
function beforeUpload(file) {
  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isLt2M) {
    ElMessage.error('图标文件大小不能超过 10MB!');
  }
  return isLt2M;
}

// 文件选择变更
function handleFileChange(file) {
  if (file.raw) {
    formData.file = file.raw;
    fileList.value = [file];

    // 如果文件名为空，自动填充文件名
    if (!formData.filename.trim()) {
      const rawName = file.raw.name.split('.')[0];
      formData.filename = rawName;
    }
  }
}

// 文件移除
function handleFileRemove() {
  formData.file = null;
  fileList.value = [];
  clearPreviewUrl();

  // 重置上传组件状态
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
    uploadRef.value.handleRemove();
  }
}

// 文件数量超出
function handleExceed() {
  ElMessage.warning('只能上传一个图标文件');
}

// 提交上传
async function submitUpload() {
  if (!formData.file) {
    ElMessage.warning('请选择要上传的图标文件');
    return;
  }

  if (!formData.filename.trim()) {
    ElMessage.warning('请输入图标名称');
    return;
  }

  uploading.value = true;

  try {
    // 确保文件名称包含正确的扩展名
    let filename = formData.filename;
    const fileExt = formData.file.name.split('.').pop().toLowerCase();

    const result = await footballService.uploadIcon(
      formData.file,
      props.iconType,
      filename,
      fileExt
    );

    if (result.success) {
      ElMessage.success('图标上传成功');
      emit('upload-success', result.data);

      // 清空表单
      formData.filename = '';
      formData.file = null;
      fileList.value = [];
      clearPreviewUrl();

      if (formRef.value) {
        formRef.value.resetFields();
      }

      // 重置上传组件
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    } else {
      ElMessage.error(result.message || '上传失败');
    }
  } catch (error) {
    console.error('上传图标失败:', error);
    ElMessage.error('上传图标时发生错误');
  } finally {
    uploading.value = false;
  }
}

// 组件销毁前清理
onBeforeUnmount(() => {
  clearPreviewUrl();
});
</script>

<style scoped>
.icon-form {
  width: 100%;
}

.upload-preview-container {
  display: flex;
  gap: 20px;
  width: 100%;
}

.upload-section {
  flex: 1;
}

.preview-section {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 15px;
  background-color: #F8F9FA;
}

/* 当预览区域是唯一显示的元素时占满宽度 */
.preview-section.full-width {
  width: 100%;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.preview-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.preview-container {
  width: 100%;
  height: 180px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: white;
  margin-bottom: 10px;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.preview-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
}

.icon-upload {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>